package while_lang.ast;

import java.util.*;

import while_lang.semantics.State;

/** Nodo del AST que representa varias sentencias en secuencia (composición).
 *  @author Leonardo Val
 */
public class Sequence extends Stmt {	
	public final Stmt[] statements;
	
	public Sequence(Stmt... statements) {
		this.statements = statements;
	}
	public Sequence(List<Stmt> statements) {
		this.statements = statements.toArray(new Stmt[statements.size()]);
	}

	@Override public String unparse() {
		StringBuilder result = new StringBuilder("{ ");
		for (int i = 0; i < statements.length; i++) {
			result.append(statements[i].unparse()).append(" ");
		}
		return result.toString() +"}";
	}

	@Override public State evaluate(State state) {

		for (Stmt st : this.statements) {
			st.evaluate(state);
		}
		
		return state;

	}
	
	public static Sequence generate(Random random, int min, int max) {
		int count = random.nextInt(5);
		Stmt[] statements = new Stmt[count];
		for (int i = 0; i < count; i++) {
			statements[i] = Stmt.generate(random, min-1, max-1);
		}
		return new Sequence(statements);
	}
	
	@Override public String toString() {
		return "Sequence("+ Arrays.toString(statements) +")";
	}

	@Override public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(statements);
		return result;
	}

	@Override public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Sequence other = (Sequence) obj;
		if (!Arrays.equals(statements, other.statements))
			return false;
		return true;
	}
	
}
